package com.example.demo.interceptor;

import com.example.demo.constants.Constants;
import com.example.demo.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //true 放行 ; false 拦截
        log.info("登录拦截...");
        HttpSession session = request.getSession(false);//如果拿不到session就会返回null
        if(session == null
                || session.getAttribute(Constants.SESSION_USER_KEY) == null
                || !StringUtils.hasLength((String)session.getAttribute(Constants.SESSION_USER_KEY))){
            //用户未登录
            log.error("用户未登录,进行拦截");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//UNAUTHORIZED的值是401
            response.getOutputStream().write("{\"ok\": false}".getBytes());
//            Result result = Result.fail();
//            response.getOutputStream().write(objectMapper.writeValueAsBytes(result).getBytes());
            response.setContentType("application/json;charset=utf-8");
            return false;
        }
        log.info("用户登录校验成功, 登录成功");
        return true;
    }

//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //true 放行 ; false 拦截
//        log.info("执行preHandle.....");
//        return false;
//    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("执行postHandle..........");
//
//
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("执行afterCompletion..........");
//
//    }
}
